package com.lynn.springboot_demo.utils;

import java.util.Arrays;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;

/**
 * @author cl
 * @Date 2020/6/18 09:42
 * 注册表工具类
 */
public class RegisterUtils {
    /**
     * 写入键、值
     *
     * @param key
     * @param value
     * @throws BackingStoreException
     */
    public static void writeValue(String key, String value) throws BackingStoreException {
        // HKEY_LOCAL_MACHINE\Software\JavaSoft\prefs下写入注册表值.
        Preferences pre = Preferences.systemNodeForPackage(RegisterUtils.class);
        pre.put(key, value);
        pre.flush();
    }

    /**
     * 根据键读取值
     *
     * @param key
     * @return
     */
    public static String getValue(String key) {
        Preferences now = Preferences.systemNodeForPackage(RegisterUtils.class);
        //没有则返回null
        return now.get(key, null);
    }

    /**
     * 获取所有key值
     *
     * @return
     * @throws BackingStoreException
     */
    public static String getKeys() throws BackingStoreException {
        Preferences pre = Preferences.systemNodeForPackage(RegisterUtils.class);
        String[] keys = pre.keys();
        return Arrays.toString(keys);

    }

    /**
     * 清除
     */
    public static void removeKey() {
        Preferences pre = Preferences.systemNodeForPackage(RegisterUtils.class);
        try {
            pre.clear();
        } catch (BackingStoreException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws BackingStoreException {
        System.out.println(RegisterUtils.getValue("registerCode"));
    }
}
